package com.hdaccp.lettingagency.controller;

import com.hdaccp.lettingagency.dao.PermissionDao;
import com.hdaccp.lettingagency.dao.RoleDao;
import com.hdaccp.lettingagency.entity.Role;
import com.hdaccp.lettingagency.pojo.PermissionBean;
import com.hdaccp.lettingagency.pojo.StateBean;
import com.hdaccp.lettingagency.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
@Scope("prototype")
public class RoleController {
    @Autowired
    private RoleService roleService ;
    @Autowired
    private RoleDao roleDao ;
    @Autowired
    private PermissionDao permissionDao ;
    @RequestMapping("/doFindAll")
    @ResponseBody
    public Map<String,Object> doFindAll(@RequestParam(value = "rname",required = false,defaultValue = "") String rname, int limit,int offset){
        Map<String,Object> map = new HashMap<>() ;
        map.put("total",roleService.findCount(rname)) ;
        map.put("rows",roleService.findAll(rname,limit,offset)) ;
        return map ;
    }
@RequestMapping("/query")
@ResponseBody
    public List<Role> query(int id){
        //查询当前用户所有拥有的角色
    Role role = roleDao.getRoleByUserId(id) ;
    //查询所有角色
    List<Role> list = roleDao.queryAll() ;
    for(Role r:list){
        if(role.getId() == r.getId()){
            r.setIschecked(true);
        }
    }
        return list ;
    }

    @RequestMapping("/queryTree")
    @ResponseBody
    public List<PermissionBean> queryTree(){
        //得到一级菜单
        List<PermissionBean> list =  permissionDao.query() ;
        for(PermissionBean permissionBean : list){
            StateBean stateBean = new StateBean() ;
            int parentId = permissionBean.getId() ;
            //得到二级菜单
            List<PermissionBean> list1 =  permissionDao.queryByParentId(parentId) ;
            permissionBean.setNodes(list1);
            permissionBean.setState(stateBean);

        }
        return  list ;
    }
}
